package com.yohann.msmservice.controller;

import com.yohann.commonutils.result.R;
import com.yohann.msmservice.service.MsmService;
import com.yohann.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.sound.midi.Soundbank;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * </p>
 *
 * @author Yohann
 * @since 2020/8/13
 */
@RestController
@RequestMapping("/msm-service")
public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
        //在redis中获取验证码
        String code = redisTemplate.opsForValue().get(phone);

        if (!StringUtils.isEmpty(code)){
            return R.ok().message("验证码已发送，请五分钟后再试！");
        }else {
            //随机生成验证码
            code = RandomUtil.getSixBitRandom();

            Map<String, Object> param = new HashMap<>();
            param.put("code",code);

            boolean isSend = msmService.send(param,phone);
            System.out.println(isSend);

            if (isSend){
                //在redis中存放验证码
                redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

                return R.ok();
            }else {
                return R.error().message("发送验证码失败！");
            }
        }
    }

    /**
     * 前端验证验证码
     * @param phone
     * @param code
     * @return
     */
    @GetMapping("inspection/{phone}/{code}")
    public R inspection(@PathVariable String phone, @PathVariable String code){
        //在redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get(phone);

        if (StringUtils.isEmpty(code)){
            return R.error();
        }

        if (redisCode.equals(code)){
            return R.ok().data("isTrue",true);
        }

        return R.error();
    }
}